<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Http\Controllers\Common\ajaxReturnJsonContent;
use App\Http\Requests\checkEmailRegister;

class RegisterController extends Controller
{
	/**
	 * 显示注册页面
	 * @return [func] [View方法加载注册页面视图]
	 */
    public function register()
    {
    	return View('home.register');
    }

    /**
     * [用于ajax验证注册时的数据是否存在]
     * @return string [一个json结果]
     */
    public function isExists(Request $request)
    {	
    	//判断是否是ajax请求
    	if (!$request->ajax()) {
    		return redirect('register');
    	}

    	//获取数据
    	$field = $request->field;
    	$content = $request->content;
    	$res = DB::table('shop_Member')->select($field)
    	                               ->where($field, $content)
    	                               ->first();
    	$arr = ajaxReturnJsonContent::returnVal($res, '已存在', '可用');
    	return json_encode($arr);
    }

    /**
     * 处理注册
     * @param  checkEmailRegister $request [description]
     * @return [type]                      [description]
     */
    public function doEmailRegister(checkEmailRegister $request)
    {

    	DB::beginTransaction();

    	//会员账号
    	$Member['email'] = $request->input('email');
    	$Member['phone'] = $request->input('phone', '');
    	$Member['password'] = password_hash($request->password, PASSWORD_DEFAULT);
    	
    	//插入数据
    	$id = DB::table('shop_Member')->insertGetId($Member);

    	if (!$id) {
    		DB::rollBack();
    		return redirect('register')->with(['warning' => '系统繁忙，添加失败']);
    	}

    	$MemberInfo['Mid'] = $id;
    	//会员信息
    	//昵称
    	$str = array_merge(range('a', 'z'),range('A', 'Z'),range('0', '9'));
    	shuffle($str);
    	$MemberInfo['nickName'] = 'xdl_';
    	for ($i = 0; $i < 12; $i++) {
    		$MemberInfo['nickName'] .= $str[$i];
    	}
    	//初始Birthday
    	$MemberInfo['Birthday'] = date("Y-m-d");

    	$id = DB::table('shop_MemberInfo')->insertGetId($MemberInfo);
    	if (!$id) {
    		DB::rollBack();
    		return redirect('register')->with(['warning' => '系统繁忙，添加失败']);
    	}
    	DB::commit();
        $request->session()->forget('code');
    	return redirect('register')->with(['warning' => '添加成功']);
    }
}
